package com.linko.intelligent.common.util;

import com.linko.intelligent.common.Constant;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;


public class JWTUtils {

    private static final Logger logger = LoggerFactory.getLogger(JWTUtils.class);

    /**
     * 获取密钥
     *
     * @return
     */
    private static Key getKeyInstance() {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(Constant.JWT_KEY);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        return signingKey;
    }

    public static String generateJWT(String subject) {
        JwtBuilder builder = Jwts.builder()
                .setSubject(subject)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + Constant.JWT_EXPIRATION))
                .signWith(SignatureAlgorithm.HS256, getKeyInstance());//设置签名使用的签名算法和签名使用的秘钥
        return builder.compact();
    }

    public static String getSubject(String jwt) {
        String subject = Jwts.parser()//得到DefaultJwtParser
                .setSigningKey(getKeyInstance())//设置签名的秘钥
                .parseClaimsJws(jwt)
                .getBody()
                .getSubject();
        return subject;
    }

    /**
     * token是否过期
     *
     * @return true：过期
     */
    public static boolean isTokenExpired(Date expiration) {
        return expiration.before(new Date());
    }

    public static Claims getClaimByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(getKeyInstance())
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            logger.debug("validate is token error ", e);
            return null;
        }
    }


    public static String updateJWT(String jwt) {
        String subject = getSubject(jwt);
        return generateJWT(subject);
    }

    public static void main(String[] as) {
        String jwt = generateJWT("abc");
        String aa = getSubject(jwt);

        System.out.println(jwt);
        System.out.println(aa);
    }
}
